programming4us
           
 
 
SQL Server

SQL server 2008 : Handling Errors (part 1)

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
12/3/2010 9:04:36 AM
In versions prior to SQL Server 2005, error-handling options were limited to the @@ERROR function. In these versions, you had to check for error conditions in a proactive way, meaning you had to monitor for error conditions within your own code and then decide what to do at the point you detected the error. In short, for every statement that could raise an error, you had to create code to handle it. As a result, codes that handled errors in SQL Server 2000 and previous versions are long, complex, and hard to maintain.

However, since the development of SQL Server 2005, you can use a TRY... CATCH block to handle errors. This block tries to run your code, and, if an error occurs, SQL Server begins execution of code that handles this error. This feature offers database developers great control of the flow of code and also lets you retrieve customizable information about the raised error.

@@ERROR Function

The @@ERROR function returns the error ID number generated by the most recent statement executed by a user. If the value returned is zero, then no error occurred. This function is available in all versions of SQL Server, and it’s the only way to handle errors in version 2000 and previous of SQL Server.

For each statement of your code that SQL Server executes, the value of @@ERROR is cleared and reset. This means that you must check the value of this function immediately following each statement that is verified or save its value to a local variable that can be checked later.

Warning

The SETERROR option of the RAISERROR statement allows you to raise an error without resetting its value. It means that SQL Server doesn’t change the @@ERROR return, although it executed a statement after the statement that raised the error.


Because of this behavior, codes developed using @@ERROR are generally complex and full of verifications using IF statements. Also, there are some errors that terminate execution when raised, which @@ERROR can’t handle, since the code that refers to this function isn’t executed. The following code shows the use of @@ERROR in a transaction in the AdventureWorks2008 database.

--Executing a defective INSERT
INSERT INTO [Production].[ProductCategory](Name, ModifiedDate)
VALUES ('Custom Category 1', '2008-20-20');

--Print the @@ERROR value
RAISERROR('The number of the error is: %u', 16, 1, @@ERROR)

An error should be returned since the date informed in the INSERT statement doesn’t exist. The following code shows the output of the execution:

Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an
out-of-range value.
The statement has been terminated.
Msg 50000, Level 16, State 1, Line 6
The number of the error is: 242

Let’s take a look at the last line of this output. SQL Server shows the message that we defined in the RAISERROR statement, plus the number 242. That value is the error number that was raised, and it can be manipulated in your code. Also, you should have noticed that the example calls the @@ERROR function immediately after the statement that can raise the error to retrieve its value before it’s reset. Let’s now change the code to see what will happen if there are two statements to be executed. See the following code:
--Executing two INSERT statements
INSERT INTO [Production].[ProductCategory](Name, ModifiedDate)
VALUES ('Custom Category 1', '2008-20-20');
INSERT INTO [Production].[ProductCategory](Name, ModifiedDate)

--Print the @@ERROR value
RAISERROR('The number of the error is: %u', 16, 1, @@ERROR)

Now, SQL Server will return interesting information. First, SQL Server will return the error of the first INSERT statement caused by the date value. Then, SQL Server will execute the second INSERT without problems. The output is as follows:

Msg 242, Level 16, State 3, Line 2
The conversion of a varchar data type to a datetime data type resulted in an
out-of-range value.
The statement has been terminated.

(1 row(s) affected)
Msg 50000, Level 16, State 1, Line 7
The number of the error is: 0


@@ERROR has some tricky behavior: although there was an error in the first statement of your code, the second statement executes correctly. Because of the last successful statement, SQL Server clears the previous value of @@ERROR and sets its value to 0. To solve this situation, you should use a local variable to store the error number and IF statements to verify the possible errors that may arise.

Another important thing that you must be aware of is the retrieval of information about the error. The @@ERROR function doesn’t provide direct access to properties like the severity level or the text of a message.In this case, you have two options: you can define your own custom error message for each possible error that can arise in the code, or you can select the error information in the sys.messages catalog view and store it in local variables. Although the last option may sound nice, most of these messages will be useless to you, especially when system errors are involved. The following code shows why retrieving error information with an @@ERROR value and then raising it as an error might be useless for your application:

--Creating the local variables
DECLARE @num INT
DECLARE @text VARCHAR(255)
DECLARE @severity INT

--Executing a defective INSERT
INSERT INTO [Production].[ProductCategory](Name, ModifiedDate)
VALUES ('Custom Category 2', '2008-20-20');

--Setting the local variable value with the @@ERROR value
SET @num = @@ERROR

--Retrieving the error data
SELECT @text = text, @severity = severity FROM [master].[sys].[messages]
WHERE message_id = @num and language_id = '1033'

--Raise the custom error message
RAISERROR(@text, @severity, 1)

You can see that the last error raised by the code shows two NULL values in the text. Those are arguments that belong to the message and were not replaced with their values when the first error arose. As a result, this error message becomes useless to the application if you don’t know which parts are the arguments and inform them in the RAISERROR statement. In short, it’s too much work for too little a result.

Keep in mind that the best way to handle errors with the @@ERROR function is to use an IF statement and define custom messages according to the error ID number that you store in a local variable.

New & Noteworthy...: @@ERROR: Just Say NO!

Although SQL Server 2008 still supports the @@ERROR function, avoid using it in new database development. This function requires a lot more work when developing code. Only if your database is to be installed on an SQL Server version 2000 or earlier should you consider using the @@ERROR function.


Other -----------------
- SQL Server 2008 : Indexing for Performance - Putting It All Together (part 5) - Filtered Indexes
- SQL Server 2008 : Indexing for Performance - Putting It All Together (part 4) - Indexing JOIN Criteria
- SQL Server 2008 : Indexing for Performance - Putting It All Together (part 3) - Covering Your Queries
- SQL Server 2008 : Indexing for Performance - Putting It All Together (part 2) - Clustered Index Seeks
- SQL Server 2008 : Indexing for Performance - Putting It All Together (part 1)
- SQL Server Integration Services : Logged and Nonlogged Operations
- SQL Server Integration Services : Using bcp (part 5)
- SQL Server Integration Services : Using bcp (part 4)
- SQL Server Integration Services : Using bcp (part 3)
- SQL Server Integration Services : Using bcp (part 2) - Fundamentals of Exporting and Importing Data
- SQL Server Integration Services : Using bcp (part 1)
- SQL Server Integration Services : Connection Projects in Visual Studio
- SQL Server Integration Services : The Package Execution Utility (part 3) - The dtutil Utility
- SQL Server Integration Services : The Package Execution Utility (part 2) - Running Packages
- SQL Server Integration Services : The Package Execution Utility (part 1)
- SQL Server Integration Services : The SSIS Designer
- SQL Server Integration Services : Running the SSIS Wizard
- SQL Server Integration Services : A Data Transformation Requirement
- SQL Server 2008 : SSIS Tools and Utilities
- SQL Server 2008 : SSIS Architecture and Concepts
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
programming4us programming4us